<template>
  <div>
    <div ref="chart" style="width: 100%; height: 400px;"></div>
  </div>
</template>

<script>
export default {
  props: {
    data: {
      type: Array,
      required: true
    }
  },
  mounted() {
    this.loadEChartsScript().then(() => {
      this.initChart();
    }).catch((err) => {
      console.error('Failed to load ECharts script:', err);
    });
  },
  methods: {
    loadEChartsScript() {
      return new Promise((resolve, reject) => {
        if (window.echarts) {
          resolve();
        } else {
          const script = document.createElement('script');
          script.src = '/echarts.js';
          script.onload = () => resolve();
          script.onerror = () => reject(new Error('ECharts script failed to load'));
          document.head.appendChild(script);
        }
      });
    },
    initChart() {
      const echarts = window.echarts;
      const chart = echarts.init(this.$refs.chart);
      const option = {
        title: {
          text: 'ECharts Example'
        },
        tooltip: {},
        xAxis: {
          type: 'category',
          data: this.data.map(item => item.name)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.data.map(item => item.value),
          type: 'bar'
        }]
      };
      chart.setOption(option);
    }
  }
};
</script>
